<!-- 新建/编辑工资模版 -->
<template>
  <div class="manage-update">
    <a-form
      layout="inline"
      ref="formRef"
      :rules="rules"
      :model="formState"
      name="basic"
      autocomplete="off"
    >
      <a-form-item label="模版名称" name="templateName">
        <a-input
          style="width: 400px"
          v-model:value="formState.templateName"
          showCount
          :maxlength="15"
        /> </a-form-item
      ><a-form-item class="manage-update-submit">
        <a-button type="primary" class="styleBtn" @click="handleSubmit"
          >保存</a-button
        >
        <a-button type="default" @click="handleCancel" class="cancelBtn"
          >取消</a-button
        >
      </a-form-item>
    </a-form>
    <div class="manage-update-create">
      <a-button
        type="primary"
        class="styleBtn"
        @click="toggleDataItem(true, null)"
        >添加数据项</a-button
      >
      <div class="manage-update-create_tips">
        <span>鼠标移入指标项，出现此</span>
        <svg-icon icon-class="drag" />
        <span>图标时，可上下拖动更改指标项展示顺序</span>
      </div>
    </div>
    <a-table
      :dataSource="state.dataSource"
      :columns="state.columns"
      :customRow="customRow"
      :pagination="false"
    >
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.key === 'action'">
          <span class="table-action">
            <span
              v-if="record.itemName !== '姓名'"
              class="table-action-item default"
              @click="toggleDataItem(true, record)"
              >编辑</span
            >
            <span
              v-if="record.itemName !== '姓名'"
              class="table-action-item default"
              @click="handleSetStatus(record)"
              >{{ record.status ? "停用" : "启用" }}</span
            >
            <span
              v-if="record.itemName !== '姓名'"
              class="table-action-item danger"
              @click="handleDelete(index)"
              >删除</span
            >
          </span>
        </template>
        <template v-if="column.key === 'date'">
          <span v-if="record.date">{{ record.date }}</span>
          <span v-else class="noTime">—</span>
        </template>
      </template>
    </a-table>
    <DataItem
      v-if="state.dataItemvisible"
      :action="state.dataItemAction"
      :record="state.dataItemRecord"
      :dataSource="state.dataSource"
      @handle-confirm="handleUpdateDataItem"
      @handle-cancel="toggleDataItem"
    />
  </div>
</template>

<script lang="ts" setup>
import { reactive, onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { Modal, message } from "ant-design-vue";
import type { FormInstance } from "ant-design-vue";
import DataItem from "./cpns/DataItem.vue";
import { ITEM_TYPE, ITEM_SOURCE } from "./config";
import {
  createSalaryTemplate,
  updateSalaryTemplate,
  salaryTemplateDetails,
} from "@/service/modules/salary/salary";

const route = useRoute();
const router = useRouter();

const formRef = ref<FormInstance>();
const rules = reactive({
  templateName: [
    {
      required: true,
      message: "请输入模版名称",
    },
  ],
});
const formState = reactive({
  templateName: "",
});
const state = reactive({
  id: route.query.id,
  dataSource: [],
  columns: [
    {
      title: "序号",
      dataIndex: "index",
      key: "index",
      customRender: ({ index }) => {
        return index + 1;
      },
    },
    {
      title: "指标名",
      dataIndex: "itemName",
      key: "itemName",
    },
    {
      title: "编码",
      dataIndex: "itemCode",
      key: "itemCode",
    },
    {
      title: "类型",
      dataIndex: "itemType",
      key: "itemType",
      customRender: ({ record }) => {
        const obj = ITEM_TYPE.find((item) => item.value === record.itemType);
        return obj?.label || "--";
      },
    },
    {
      title: "数据来源",
      dataIndex: "itemSource",
      key: "itemSource",
      customRender: ({ record }) => {
        const obj = ITEM_SOURCE.find(
          (item) => item.value === record.itemSource
        );
        return obj?.label || "--";
      },
      rowDrag: true,
    },
    {
      title: "编辑时间",
      dataIndex: "date",
      key: "date",
    },
    {
      title: "操作",
      key: "action",
      rowDrag: true,
    },
  ],
  dataItemAction: "",
  dataItemvisible: false,
  dataItemRecord: {},
});
const prevPage = ref<number>(0);
const nextPage = ref<number>(0);
// 表格行拖动
const customRow = (record, index) => {
  return {
    props: {},
    style: {
      cursor: "pointer",
    },
    // 鼠标移入
    onMouseenter: (event) => {
      // 兼容IE
      const ev = event || window.event;
      ev.target.draggable = true; // 让你要拖动的行可以拖动，默认不可以
    },
    // 开始拖拽
    onDragstart: (event) => {
      // 兼容IE
      const ev = event || window.event;
      // 阻止冒泡
      ev.stopPropagation();
      // 得到源目标数据序号
      prevPage.value = index;
    },
    // 拖动元素经过的元素
    onDragover: (event) => {
      // 兼容 IE
      const ev = event || window.event;
      // 阻止默认行为
      ev.preventDefault();
    },
    // 鼠标松开
    onDrop: (event) => {
      // 兼容IE
      const ev = event || window.event;
      // 阻止冒泡
      ev.stopPropagation();
      // 得到目标数据序号
      nextPage.value = index;
      // 这里就是让数据位置互换，让视图更新
      [state.dataSource[prevPage.value], state.dataSource[nextPage.value]] = [
        state.dataSource[nextPage.value],
        state.dataSource[prevPage.value],
      ];
    },
  };
};
// 获取工资模板详细信息
const getSalaryTemplateDetails = async () => {
  const { data } = await salaryTemplateDetails(state.id);
  state.dataSource = data.items.map((item) => {
    return {
      itemName: item.itemName,
      itemCode: item.itemCode,
      itemType: item.itemType,
      itemSource: item.itemSource,
      status: item.status,
      date: item.updateTime,
    };
  });
  formState.templateName = data.templateName;
};
// 取消
const handleCancel = () => {
  router.go(-1);
};
// 保存
const handleSubmit = () => {
  formRef.value
    ?.validate()
    .then(async () => {
      const data = {
        templateName: formState.templateName,
        items: [...state.dataSource],
      };
      let updateApi = createSalaryTemplate;
      if (state.id) {
        updateApi = updateSalaryTemplate;
        data.id = state.id;
      }
      const { msg } = await updateApi(data);
      message.success(msg || "保存成功");
      router.push({
        path: "/salary/manage",
      });
    })
    .catch(() => {});
};
// 打开/关闭添加/编辑数据项弹框
const toggleDataItem = (value: boolean, record: any) => {
  state.dataItemvisible = value;
  if (value) {
    if (record) {
      state.dataItemAction = "update";
    } else {
      state.dataItemAction = "create";
    }
    state.dataItemRecord = {
      itemName: record?.itemName || "",
      itemCode: record?.itemCode || "",
      itemType: record?.itemType || 2,
      itemSource: record?.itemSource || 1,
      date: record?.date || "",
      status: record?.status || 1,
    };
  }
};
// 添加/编辑数据项
const handleUpdateDataItem = (record: any) => {
  const index = state.dataSource.findIndex(
    (item) => item.itemCode === record.itemCode
  );
  if (index !== -1) {
    state.dataSource.splice(index, 1, { ...record });
  } else {
    state.dataSource.push({
      ...record,
    });
  }
  state.dataItemvisible = false;
};
// 启用/停用
const handleSetStatus = (record: any) => {
  Modal.confirm({
    title: `是否确认${record.status ? "停用" : "启用"}此数据项`,
    content: "",
    onCancel: () => {},
    onOk: () => {
      state.dataSource = state.dataSource.map((item) => {
        if (item.itemCode === record.itemCode) {
          item.status = record.status ? 0 : 1;
        }
        return item;
      });
    },
  });
};
// 删除
const handleDelete = (index: number) => {
  Modal.confirm({
    title: `是否确认删除此数据项`,
    content: "",
    onCancel: () => {},
    onOk: () => {
      state.dataSource.splice(index, 1);
    },
  });
};
onMounted(() => {
  if (state.id) {
    getSalaryTemplateDetails();
  } else {
    state.dataSource.push({
      itemName: "姓名",
      itemCode: "001",
      itemType: 1,
      itemSource: 2,
      date: "",
      status: 1,
    });
  }
});
</script>

<style lang="less" scoped>
.campus-salary-web {
  cursor: pointer;
}
.manage-update {
  height: 100%;
  overflow: scroll;
  padding: 24px;
  background: #fff;
  border-radius: 10px;
  /deep/ .ant-form-item-control {
    position: relative;
  }
  /deep/ .ant-form-item-explain {
    position: absolute;
  }
  /deep/ .ant-form-inline .ant-form-item-with-help {
    margin-bottom: 0;
  }
  /deep/ .ant-table-row {
    cursor: url("../../assets/img/drag.png"), auto !important;
  }
  .noTime {
    font-size: 14px;
    line-height: 56px;
    color: #aaaeb2;
  }
  &-submit {
    flex: 1;
    margin-right: 0;
    text-align: right;
  }
  &-create {
    display: flex;
    align-items: center;
    margin: 24px 0;
    &_tips {
      margin-left: 17px;
      font-size: 14px;
      color: #aaaeb2;
    }
  }
  .styleBtn,
  .cancelBtn {
    border-radius: 6px;
    background: #3e77fa;
    border: 1px solid #3e77fa;
  }
  .cancelBtn {
    background: #ffffff;
    color: #3e77fa;
  }
}
</style>
